from datetime import datetime

from django.db.models import Q

from gis.common.exceptions import BizException
from gis.common.django_ext.models import paginate
from itpay.core.sys.models import Bulletin
from itpay.core.mch import service as mch_service
from .errors import *


def add_bulletin(value, start_time, end_time, mch_ids):
    assert value
    assert start_time
    assert end_time

    m_bulletin = Bulletin.objects.create(value=value, start_time=start_time, end_time=end_time)

    mch_service.bind_mch_to_bulletin(m_bulletin, mch_ids)

    return m_bulletin.to_dict()


def get_bulletin(bulletin_id, with_mch_info=False):
    assert bulletin_id
    bulletin = _get_bulletin(bulletin_id)
    if not bulletin:
        raise BizException(ERROR_BULLETIN_NOT_EXISTS)
    return bulletin.to_dict(return_many_to_many=with_mch_info)


def update_bulletin(bulletin_id, value, start_time, end_time, mch_ids=None):
    assert bulletin_id
    bulletin = _get_bulletin(bulletin_id)
    if not bulletin:
        raise BizException(ERROR_BULLETIN_NOT_EXISTS)
    bulletin.value = value
    bulletin.start_time = start_time
    bulletin.end_time = end_time
    if mch_ids is not None:
        bulletin.mchs.clear()
        mch_service.bind_mch_to_bulletin(bulletin, mch_ids)
    bulletin.save()


def delete_bulletin(bulletin_id):
    assert bulletin_id
    m_bulletin = _get_bulletin(bulletin_id)
    m_bulletin.mchs.clear()
    m_bulletin.delete()


def _get_bulletin(bulletin_id):
    m_bulletin = Bulletin.objects.filter(pk=bulletin_id).first()
    return m_bulletin


def list_bulletin(page_no, page_size, is_flash=None, mch_ids=None, with_mch_info=False, value=None,
                  start_time_begin=None, start_time_end=None, end_time_begin=None, end_time_end=None):
    local_time = datetime.now()
    query = Bulletin.objects.all().distinct()
    if is_flash is not None:
        if is_flash:
            query = query.filter(start_time__lte=local_time, end_time__gte=local_time)
        else:
            query = query.filter(Q(start_time__gte=local_time) | Q(end_time__lte=local_time))
    if mch_ids:
        query = query.filter(mchs__in=mch_ids)
    if value:
        query = query.filter(value__contains=value)
    if start_time_begin:
        query = query.filter(start_time__gte=start_time_begin)
    if start_time_end:
        query = query.filter(start_time__lte=start_time_end)
    if end_time_begin:
        query = query.filter(end_time__gte=end_time_begin)
    if end_time_end:
        query = query.filter(end_time__lte=end_time_end)
    return query.count(), [e.to_dict(return_many_to_many=with_mch_info) for e in
                           paginate(query.order_by('-updated_at'), page_no, page_size)]
